import { PlusOutlined } from '@ant-design/icons';
import { Button, Divider, message, Popconfirm, Select } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import Bmap from '@/components/Bmap/index.jsx';
import FormItem from 'antd/lib/form/FormItem';
import {
  queryRule,
  updateRule,
  addRule,
  removeRule,
  queryPoliceStationRule,
  queryStreetRule,
} from './service';
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param payload
 */

const handleUpdate = async (payload) => {
  const hide = message.loading('正在修改');

  try {
    await updateRule(payload);
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (payload, actionRef) => {
  const hide = message.loading('正在删除');

  try {
    await removeRule(payload);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [createEditModalVisible, handleEditModalVisible] = useState(false);
  const [createMapModalVisible, handleMapModalVisible] = useState(false);
  const [formValue, setFormValue] = useState(null);
  const [pointData, setPointData] = useState({});
  const [count, setCount] = useState({});
  const [policeValues, setPoliceValues] = useState([]);
  const [streetValues, setStreetValues] = useState([]);
  const [policeId, setPoliceList] = useState(null);
  const [streetId, setStreetList] = useState(null);
  const [areaId, setAreaId] = useState(null);
  const [mapValue, setMapValue] = useState({});
  const actionRef = useRef();
  const formRef = useRef();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const handleChoicePlace = (e) => {
    if (e.hasOwnProperty('point')) {
      setPointData(e);
    }
  };
  const handleQueryPolice = async () => {
    try {
      const response = await queryPoliceStationRule({ type: 4 });
      const { data } = response;
      setPoliceValues(data);
      return true;
    } catch (error) {
      return false;
    }
  };
  const handleQueryStreet = async () => {
    try {
      const response = await queryStreetRule({ type: 6 });
      const { data } = response;
      setStreetValues(data);
      return true;
    } catch (error) {
      return false;
    }
  };
  useEffect(() => {
    handleQueryStreet();
    handleQueryPolice();
  }, []);
  const columns = [
    {
      title: '社区名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '社区电话',
      dataIndex: 'tel',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '联系人姓名',
      dataIndex: 'contacts',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '所属街道办',
      dataIndex: 'parentId',
      valueType: 'text',
      // hideInSearch: true,
      render: (_, record) => {
        return streetValues.map((item) => {
          if (_ == item.id) {
            return <span>{item.name}</span>;
          }
        });
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <>
            <FormItem name="parentId">
              <Select
                onChange={(value, info) => {
                  setStreetList(value);
                  setAreaId(info.areaId);
                }}
                value={streetId}
                placeholder="请选择"
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {streetValues.map((item_in, index) => {
                  return (
                    <Option key={index} areaId={item_in.areaId} value={item_in.id}>
                      {item_in.name}
                    </Option>
                  );
                })}
              </Select>
            </FormItem>
          </>
        );
      },
    },
    {
      title: '所属派出所',
      dataIndex: 'policeId',
      valueType: 'text',
      // hideInSearch: true,
      render: (_, record) => {
        return policeValues.map((item) => {
          if (_ == item.id) {
            return <span>{item.name}</span>;
          }
        });
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <>
            <FormItem name="policeId">
              <Select
                onChange={(value) => {
                  setPoliceList(value);
                }}
                value={policeId}
                placeholder="请选择"
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                {policeValues.map((item_in, index) => {
                  return (
                    <Option key={index} value={item_in.id}>
                      {item_in.name}
                    </Option>
                  );
                })}
              </Select>
            </FormItem>
          </>
        );
      },
    },
    {
      title: '社区位置',
      dataIndex: 'position',
      valueType: 'text',
      width: 200,
      hideInSearch: true,
      render: (_, record) => {
        return (
          <div
            style={{ cursor: 'pointer', color: '#1890ff' }}
            onClick={() => {
              setMapValue({
                address: record.address ? record.address : '',
                point: {
                  lat: record.lat,
                  lng: record.lng,
                },
                device: true,
              });
              handleMapModalVisible(true);
            }}
          >
            查看
          </div>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <>
            <Bmap
              size={{ height: 400 }}
              value={pointData}
              onChange={(e) => {
                handleChoicePlace(e);
              }}
            />
          </>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 140,
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleEditModalVisible(true);
              setPointData({
                address: record.address,
                point: {
                  lat: record.lat,
                  lng: record.lng,
                },
              });
              setStreetList(record.parentId);
              setPoliceList(record.policeId);
              setAreaId(record.areaId);
              setFormValue(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <Popconfirm
            placement="top"
            title="确定要删除吗?"
            onConfirm={() => {
              handleRemove(record.id, actionRef);
            }}
            okText="Yes"
            cancelText="No"
          >
            <a onClick={() => {}}>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="社区列表"
        actionRef={actionRef}
        formRef={formRef}
        rowKey="id"
        bordered
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              handleModalVisible(true);
              setPoliceList(null);
              setStreetList(null);
              setAreaId(null);
              setPointData({});
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params, sorter, filter) => {
          const type = { type: 7 };
          Object.assign(params, type);
          return queryRule({ ...params, sorter, filter });
        }}
        postData={(params) => {
          const { list, total } = params;
          setCount(total);
          return list||[];
        }}
        beforeSearchSubmit={(payload) => {
          // console.log(payload);
          // console.log(policeId);
          // console.log(streetId);
          // if (policeId) {
          //   payload.policeId = policeId;
          // }
          // if (streetId) {
          //   payload.streetId = streetId;
          // }
          return payload;
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
        rowSelection={false}
        options={false}
      />
      <CreateForm
        title="新增社区"
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
      >
        <ProTable
          onSubmit={async (value) => {
            value.type = 7;
            const { point } = pointData;
            value.address = point.address;
            value.lng = point.lng;
            value.lat = point.lat;
            value.policeId = policeId;
            value.parentId = streetId;
            value.areaId = areaId;
            const success = await handleAdd(value);
            setPoliceList(null);
            setStreetList(null);
            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        title="修改社区"
        onCancel={() => handleEditModalVisible(false)}
        modalVisible={createEditModalVisible}
      >
        <ProTable
          onSubmit={async (value) => {
            const { point } = pointData;
            value.address = point.address;
            value.lng = point.lng;
            value.lat = point.lat;
            value.id = formValue.id;
            value.type = formValue.type;
            value.version = formValue.version + 1;
            value.policeId = policeId;
            value.parentId = streetId;
            value.areaId = areaId;
            const success = await handleUpdate(value);
            setPoliceList(null);
            setStreetList(null);
            setAreaId(null);
            if (success) {
              handleEditModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
          form={{ initialValues: formValue }}
        />
      </CreateForm>
      <CreateForm
        onCancel={() => handleMapModalVisible(false)}
        modalVisible={createMapModalVisible}
        title="社区位置"
      >
        <Bmap size={{ width: 400, height: 350, marginLeft: '8%' }} value={mapValue} />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
